package com.suny.dingd_demo.config;

import de.codecentric.boot.admin.server.config.AdminServerProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.csrf.CookieCsrfTokenRepository;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    private final AdminServerProperties adminServer;

    public SecurityConfig(AdminServerProperties adminServer) {
        this.adminServer = adminServer;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        String adminContextPath = adminServer.getContextPath();
        
        http.authorizeRequests()
                .antMatchers(adminContextPath + "/assets/**").permitAll()
                .antMatchers(adminContextPath + "/login").permitAll()
                .antMatchers(adminContextPath + "/actuator/**").permitAll()
                .antMatchers(adminContextPath + "/instances/**").permitAll()
                .antMatchers(HttpMethod.GET, adminContextPath + "/notifications/filters").permitAll()
                .antMatchers(adminContextPath + "/notifications/filter").permitAll()
                .anyRequest().authenticated()
                .and()
            .formLogin()
                .loginPage(adminContextPath + "/login")
                .successHandler((req, res, auth) -> res.sendRedirect(adminContextPath + "/"))
                .and()
            .logout()
                .logoutUrl(adminContextPath + "/logout")
                .and()
            .httpBasic()
                .and()
            .csrf()
                .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
                .ignoringRequestMatchers(
                    new AntPathRequestMatcher(adminContextPath + "/instances", HttpMethod.POST.toString()),
                    new AntPathRequestMatcher(adminContextPath + "/instances/*", HttpMethod.DELETE.toString()),
                    new AntPathRequestMatcher(adminContextPath + "/actuator/**")
                );
    }
} 